#
# PodTrack.py
#
# This work is released under the GNU GPL, version 2 or later.
#
from Track import *
from LMusicPlayer import *
from LsongsDevices import *
import time, re, os
#from iTunesDB import *
import crushToAscii

class PodTrack(Track):
	def __init__(self,library = None):
		Track.__init__(self,library)
		self.player= True
		self.kind = "Pod Track"
		self.location = "ipod:"
		self.image = None

	def play(self,playlist = None):
		pass
		#LMusicPlayer.playTrack(self,self._library,playlist)

	def cleanup(self,s):
		return tr(crushToAscii.crush(s),{'/':'-',' ':'_',':':'_','\\':'_','<':'(','>':')',';':'_','|':'_'})

	def fromSong(self,song):
		self.song = song
		try: self.title = song.title
		except: pass
		try: self.artist = song.artist
		except: pass
		try: self.album = song.album
		except: pass
		try: self.genre = song.genre
		except: pass
		try: self.composer = song.composer
		except: pass
		try: self.grouping = song.grouping
		except: pass
		try: self.comment = song.comment
		except: pass
		try: self.kind = song.fileType
		except: pass
		try:
			self.location = song.location
		except: pass
		self.trackID = song.id
		self.compilation = song.compilation
		self.rating = song.rating
		self.size = song.size
		self.totalTime = song.duration
		self.trackNum = song.trackNumber
		self.trackCount = song.trackCount
		self.discNum = song.discNumber
		self.bitRate = song.bitRate*1000
		self.sampleRate = song.sampleRate
		#self.originalLocation = self.cleanup(os.path.split(self.nativeLocation())[1])
		self.originalLocation = self.cleanup(self.title)
		#print self.kind,self.originalLocation
		if self.kind.startswith("MPEG"):
			if not self.originalLocation.endswith(".mp3"):
				self.originalLocation += ".mp3"
		elif self.kind.startswith("AAC"):
			if not self.originalLocation.endswith(".m4a"):
				self.originalLocation += ".m4a"
		elif self.kind.startswith("WAV"):
			if not self.originalLocation.endswith(".wav"):
				self.originalLocation += ".wav"
		else:
			self.originalLocation += ".mp3"

	def nativeLocation(self,podPath = None):
		if podPath==None: podPath = self.location
		return os.path.join(self._library.basePath,podPath.replace(':','/')[1:])
		
	def download(self,callback = None, data = None):
		tmpPath = os.environ.get('TMP','/tmp')
		#print "tmpPath",tmpPath,"location",self.originalLocation
		#fromPath = self.nativeLocation()
		toPath = os.path.join(tmpPath,self.originalLocation)
		#print "downloading track from",fromPath,"to",toPath,"of size",self.size
		#try: copyFile(fromPath,toPath,callback,data,self.size)
		#except: pass
		self.song.download(toPath,callback,data)
		return toPath
	
	def kill(self):
		path = self.nativeLocation()
		try:
			#print "attempting to remove file",path
			os.remove(path)
		except: pass
	
def copyFileObj(fsrc, fdst, callback,data,size,length=16*1024):
	"""copy data from file-like object fsrc to file-like object fdst"""
	bytes = 0
	while 1:
		buf = fsrc.read(length)
		if not buf:
			if callback: callback(size,size,data)
			break
		bytes = bytes+len(buf)
		fdst.write(buf)
		#print bytes,size
		if callback: callback(bytes,size,data)

def copyFile(src, dst,callback = None,data = None,size = None):
	"""Copy data from src to dst"""
	fsrc = None
	fdst = None
	# check for same pathname; all platforms
	_src = os.path.normcase(os.path.abspath(src))
	_dst = os.path.normcase(os.path.abspath(dst))
	if _src == _dst:
		return
	try:
		fsrc = open(src, 'rb')
		fdst = open(dst, 'wb')
		copyFileObj(fsrc, fdst,callback,data,size)
	finally:
		if fdst:
			fdst.close()
		if fsrc:
			fsrc.close()

